package com.web.hilover.controller;

import com.web.hilover.entity.*;
import com.web.hilover.service.*;
import com.web.hilover.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import jakarta.servlet.http.HttpSession;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@Slf4j
public class AdminController {
    
    @Autowired
    private StatService statService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CoupleService coupleService;
    
    @Autowired
    private CommentService commentService;
    
    @Autowired
    private QuoteService quoteService;
    
    @Autowired
    private TimelineService timelineService;
    
    @GetMapping("")
    public String dashboard(Model model) {
        // 获取统计数据
        Map<String, Integer> stats = statService.getDashboardStats();
        Map<String, Object> activities = statService.getRecentActivities();
        
        model.addAttribute("stats", stats);
        model.addAttribute("recentComments", activities.get("recentComments"));
        model.addAttribute("recentCouples", activities.get("recentCouples"));
        
        // 添加布局需要的参数
        model.addAttribute("title", "控制台");
        model.addAttribute("active", "dashboard");
        model.addAttribute("page", "dashboard");
        
        return "admin/common/layout";  // 返回布局页面
    }
    
    @GetMapping("/users")
    public String users(Model model) {
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        
        model.addAttribute("title", "用户管理");
        model.addAttribute("active", "users");
        model.addAttribute("page", "users");
        
        return "admin/common/layout";
    }
    
    @GetMapping("/couples")
    public String couples(Model model) {
        List<Map<String, Object>> couples = coupleService.getAllCouplesWithDetail();
        model.addAttribute("couples", couples);
        
        model.addAttribute("title", "情侣管理");
        model.addAttribute("active", "couples");
        model.addAttribute("page", "couples");
        
        return "admin/common/layout";
    }

    @GetMapping("/couples/{id}/timeline")
    public String timeline(Model model,@PathVariable Long id) {
        List<Timeline> timelines = timelineService.getTimelinesByCouple(id);

        model.addAttribute("timeline", timelines);

        model.addAttribute("title", "时间线管理");
        model.addAttribute("active", "timeline");
        model.addAttribute("page", "timeline");

        return "admin/common/layout";
    }
    
    @GetMapping("/comments")
    public String comments(Model model) {
        List<Map<String, Object>> comments = commentService.getAllCommentsWithDetail();
        model.addAttribute("comments", comments);
        
        model.addAttribute("title", "评论管理");
        model.addAttribute("active", "comments");
        model.addAttribute("page", "comments");
        
        return "admin/common/layout";
    }

    @GetMapping("/quotes")
    public String quotes(Model model) {
        List<Quote> quotes = quoteService.getAllQuotes();
        model.addAttribute("quotes", quotes);

        model.addAttribute("title", "名言管理");
        model.addAttribute("active", "quotes");
        model.addAttribute("page", "quotes");

        return "admin/common/layout";
    }


    
    // 获取用户信息
    @GetMapping("/users/{id}")
    @ResponseBody
    public User getUser(@PathVariable Long id) {
        return userService.getUserById(id);
    }
    
    // 更新用户
    @PostMapping("/users/{id}/update")
    @ResponseBody
    public Map<String, Object> updateUser(@PathVariable Long id,
                                        @RequestParam String nickname,
                                        @RequestParam Integer role) {
        try {
            log.info("Updating user: id={}, nickname={}, role={}", id, nickname, role);
            User user = userService.getUserById(id);
            if (user == null) {
                return Map.of("success", false, "message", "用户不存在");
            }
            
            user.setNickname(nickname);
            user.setRole(role);
            boolean success = userService.updateUser(user);
            
            if (!success) {
                return Map.of("success", false, "message", "更新失败");
            }
            
            return Map.of("success", true);
        } catch (Exception e) {
            log.error("Update user failed", e);
            return Map.of("success", false, "message", e.getMessage());
        }
    }
    
    // 删除用户
    @PostMapping("/users/{id}/delete")
    @ResponseBody
    public Map<String, Object> deleteUser(@PathVariable Long id) {
        try {
            userService.deleteUser(id);
            return Map.of("success", true);
        } catch (Exception e) {
            return Map.of("success", false, "message", e.getMessage());
        }
    }
    
    @PostMapping("/couples/{id}/update")
    @ResponseBody
    public Map<String, Object> updateCouple(@PathVariable Long id,
                                          @RequestParam(required = false) Integer visibility,
                                          @RequestParam(required = false) Integer likes) {
        try {
            Couple couple = coupleService.getCoupleById(id);
            if (couple == null) {
                return Map.of("success", false, "message", "情侣不存在");
            }
            
            if (visibility != null) {
                couple.setVisibility(visibility);
            }
            if (likes != null) {
                couple.setLikes(likes);
            }
            
            coupleService.updateCouple(couple);
            return Map.of("success", true);
        } catch (Exception e) {
            log.error("Update couple failed", e);
            return Map.of("success", false, "message", e.getMessage());
        }
    }
    
    @PostMapping("/couples/{id}/delete")
    @ResponseBody
    public Map<String, Object> deleteCouple(@PathVariable Long id) {
        try {
            coupleService.deleteCouple(id);
            return Map.of("success", true);
        } catch (Exception e) {
            log.error("Delete couple failed", e);
            return Map.of("success", false, "message", e.getMessage());
        }
    }
    
    @PostMapping("/comments/{id}/delete")
    @ResponseBody
    public Map<String, Object> deleteComment(@PathVariable Long id) {
        try {
            commentService.deleteComment(id);
            return Map.of("success", true);
        } catch (Exception e) {
            log.error("Delete comment failed", e);
            return Map.of("success", false, "message", e.getMessage());
        }
    }
    
    @GetMapping("/quotes/{id}")
    @ResponseBody
    public Quote getQuote(@PathVariable Long id) {
        return quoteService.getQuoteById(id);
    }
    
    @PostMapping("/quotes/add")
    @ResponseBody
    public Map<String, Object> addQuote(@RequestParam String content,
                                       @RequestParam String author,
                                       @RequestParam Integer status) {
        try {
            Quote quote = Quote.builder()
                    .content(content)
                    .author(author)
                    .status(status)
                    .build();
            quoteService.addQuote(quote);
            return Map.of("success", true);
        } catch (Exception e) {
            log.error("Add quote failed", e);
            return Map.of("success", false, "message", e.getMessage());
        }
    }
    
    @PostMapping("/quotes/{id}/update")
    @ResponseBody
    public Map<String, Object> updateQuote(@PathVariable Long id,
                                         @RequestParam String content,
                                         @RequestParam String author,
                                         @RequestParam Integer status) {
        try {
            Quote quote = quoteService.getQuoteById(id);
            if (quote == null) {
                return Map.of("success", false, "message", "名言不存在");
            }
            
            quote.setContent(content);
            quote.setAuthor(author);
            quote.setStatus(status);
            
            quoteService.updateQuote(quote);
            return Map.of("success", true);
        } catch (Exception e) {
            log.error("Update quote failed", e);
            return Map.of("success", false, "message", e.getMessage());
        }
    }
    
    @PostMapping("/quotes/{id}/delete")
    @ResponseBody
    public Map<String, Object> deleteQuote(@PathVariable Long id) {
        try {
            quoteService.deleteQuote(id);
            return Map.of("success", true);
        } catch (Exception e) {
            log.error("Delete quote failed", e);
            return Map.of("success", false, "message", e.getMessage());
        }
    }

    @PostMapping("/timeline/{id}/delete")
    @ResponseBody
    public Map<String, Object> deleteTimeLine(@PathVariable Long id) {
        try {
            timelineService.deleteTimeline(id);
            return Map.of("success", true);
        } catch (Exception e) {
            log.error("Delete timeline failed", e);
            return Map.of("success", false, "message", e.getMessage());
        }
    }
    
    @GetMapping("/couples/{id}/timelines")
    @ResponseBody
    public Map<String, Object> getCoupleTimelines(@PathVariable Long id) {
        try {
            List<Timeline> timelines = timelineService.getTimelinesByCouple(id);
            if (timelines.size() > 100) {
                timelines = timelines.subList(0, 100);
            }
            return Map.of(
                "success", true,
                "timelines", timelines
            );
        } catch (Exception e) {
            log.error("Get couple timelines failed", e);
            return Map.of(
                "success", false,
                "message", e.getMessage()
            );
        }
    }
    
    @PostMapping("/couples/{id}/ai-summary")
    @ResponseBody
    public Map<String, Object> generateAISummary(@PathVariable Long id, 
                                               @RequestBody Map<String, List<Timeline>> request) {
        try {
            List<Timeline> timelines = request.get("timelines");
            
            // 构建发送给AI的内容
            StringBuilder prompt = new StringBuilder();
            prompt.append("你是一个专业的情感总结机器人。请根据以下时间轴记录，总结这对情侣的故事，请用评论的方式，尽量让这个评论显得幽默有趣：\n\n");
            
            for (Timeline timeline : timelines) {
                prompt.append("时间: ").append(timeline.getEventDate())
                      .append("\n内容: ").append(timeline.getContent())
                      .append("\n\n");
            }
            
            // 调用智谱AI的GLM-4接口
            String apiKey = ""; // 替换API Key qq575732022
            String url = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);
            
            Map<String, Object> message = Map.of(
                "role", "user",
                "content", prompt.toString()
            );
            
            Map<String, Object> requestBody = Map.of(
                "model", "glm-4-plus",
                "messages", List.of(message)
            );
            
            RestTemplate restTemplate = new RestTemplate();
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            
            ResponseEntity<Map> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                entity,
                Map.class
            );
            
            Map responseBody = response.getBody();
            List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");
            Map<String, Object> choice = choices.get(0);
            Map<String, String> messageResponse = (Map<String, String>) choice.get("message");
            String content = messageResponse.get("content");
            
            return Map.of(
                "success", true,
                "content", content
            );
            
        } catch (Exception e) {
            log.error("Generate AI summary failed", e);
            return Map.of(
                "success", false,
                "message", e.getMessage()
            );
        }
    }
    
    @PostMapping("/couples/{id}/comment")
    @ResponseBody
    public Map<String, Object> addComment(@PathVariable Long id, 
                                        @RequestBody Map<String, String> request,
                                        HttpSession session) {
        try {
            String content = request.get("content");
            User loginUser = (User) session.getAttribute("loginUser");
            
            Comment comment = Comment.builder()
                    .coupleId(id)
                    .userId(loginUser.getId())
                    .content(content)
                    .likes(0)
                    .build();
            
            commentService.addComment(comment);
            return Map.of("success", true);
        } catch (Exception e) {
            log.error("Add comment failed", e);
            return Map.of(
                "success", false,
                "message", e.getMessage()
            );
        }
    }

} 